const Model = require('./model')
const BaseMongo = require('../base')
const { stateKeys } = require('../base/model')

/**
 * 封装
 */
class PackageMongo extends BaseMongo{

	constructor () {
		super()
	}

	/**
	 * 更新数据
	 * @param data 需要更新的数据
	 * @returns {Promise<*>}
	 */
	static update(data) {
		return Model.updateOne(
			{_id: this.objId(data.id)},
			this.getJson(data,
        ['name', 'cover', 'type', 'content', 'describe', 'url', 'date']))
	}

	/**
	 * 获取数据列表
	 * @param data  type: 类型 searchKey: 关键字 page: 页数 count: 一个个数
	 * @returns {Promise<void>}
	 */
	static find(data) {
		const params = { $or: [
				{stateKey: stateKeys.NORMAL},
				{stateKey: {$exists: false}}
			]}
		if (data.type) {
			params.type = data.type
		}
    if (data.searchKey) {
      const reg = { $regex: `${data.searchKey}`, "$options": "i" }
      switch (data.searchType) {
        case '0':
          params['$or'] = [
            {'name': reg},
            {'describe': reg},
            {'content': reg}
          ]
          break
        case '1':
          params['name'] = reg
          break
        case '2':
          params['describe'] = reg
          break
        case '3':
          params['content'] = reg
          break
      }
    }
		let field = this.existparameter(['name', 'cover', 'type', 'describe', 'url', 'date'])
		const skip = (data.page - 1) * data.count
		const model = Model.find(params, field).skip(skip).limit(data.count)
		model.sort({'date': -1})
		return model.exec()
	}

	/**
	 * 查询某个字段的不同数据数组
	 * @param key 字段名
	 * @returns {Promise<*>}
	 */
  static distinct(key) {
    return Model.distinct(key, {
			$or: [
				{stateKey: stateKeys.NORMAL},
				{stateKey: {$exists: false}}
			]
		})
  }
}

/**
 * 设置当前模型
 */
PackageMongo.model = Model

/**
 * 添加字段数组
 * @type {Array}
 */
PackageMongo.fieldArr = ['name', 'cover', 'type', 'content', 'describe', 'url', 'date']

module.exports = PackageMongo
